﻿namespace PowerSong.UserInterface
    {
    using System.Windows;
    using PowerSong.SongDatabase;
    using System;

    /// <summary>
    /// Interaction logic for EditLicenseWindow.xaml
    /// </summary>
    public partial class EditLicenseWindow : Window
        {

        private License existingLicense = null;

        public EditLicenseWindow(License existingLicense = null)
            {
            
            InitializeComponent();
            this.existingLicense = existingLicense;
            this.Title = existingLicense == null ? "New License" : "Edit License - " + existingLicense.Name;

            // Show existing license details
            if (existingLicense != null)
                {
                NameTextBox.Text = existingLicense.Name;
                NumberTextBox.Text = existingLicense.Number;
                DetailsTextBox.Text = existingLicense.Description;
                }

            }

        private void CancelButton_Click(object sender, RoutedEventArgs e)
            {
            this.DialogResult = false;
            }

        private void OKButton_Click(object sender, RoutedEventArgs e)
            {

            try
                {

                // Ensure a name has been specified
                if (string.IsNullOrEmpty(NameTextBox.Text))
                    {
                    throw new Exception("Please specify a name for the license.");
                    }

                // Create a new license object, or edit the existing license object
                var license = existingLicense == null ? new License() : this.existingLicense;

                // Write to a license object
                license.Name = NameTextBox.Text;
                license.Number = NumberTextBox.Text;
                license.Description = DetailsTextBox.Text;

                // Save the license
                State.Database.Licenses.Write(license);

                // Close the window
                this.DialogResult = true;

                }
            catch (Exception ex)
                {
                Utilities.ShowErrorMessage("Cannot Save License", ex.Message);
                }

            }

        }

    }
